package pure.coding.web.initializer;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.CharacterEncodingFilter;

import com.google.code.kaptcha.servlet.KaptchaServlet;

/**
 * servlet和filter
 * 
 * @author Young
 *
 */
public class StartUpInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext sc) throws ServletException {
		// 添加kaptcha servlet
		addKaptchaServlet(sc);
		// 添加spring编码过滤器
		addCharsetEncodingFilter(sc);
	}

	/**
	 * CharacterEncodingFilter编码过滤器
	 * @param sc
	 */
	private void addCharsetEncodingFilter(ServletContext sc) {
		javax.servlet.FilterRegistration.Dynamic charsetEncodingFilter = sc
				.addFilter("charsetEncoding", CharacterEncodingFilter.class);
		charsetEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
		Map<String, String> initParameters = new HashMap<>();
		initParameters.put("encoding", "UTF-8");
		initParameters.put("forceEncoding", "true");
		charsetEncodingFilter.setInitParameters(initParameters);
	}

	/**
	 * Kaptcha验证码
	 * @param sc
	 */
	private void addKaptchaServlet(ServletContext sc) {
		javax.servlet.ServletRegistration.Dynamic kaptchaServlet = sc
				.addServlet("kaptchaServlet", KaptchaServlet.class);
		kaptchaServlet.addMapping("/kaptcha.jpg");
		Map<String, String> initParameters = new HashMap<>();
		initParameters.put("kaptcha.image.width", "60");
		initParameters.put("kaptcha.image.height", "25");
		initParameters.put("kaptcha.noise.impl",
				"com.google.code.kaptcha.impl.NoNoise");
		initParameters.put("kaptcha.textproducer.char.string",
				"0123456789abcdefghijklmnopqrstuvwxyz");
		initParameters.put("kaptcha.textproducer.char.length", "4");
		initParameters.put("kaptcha.textproducer.font.size", "20");
		initParameters.put("kaptcha.obscurificator.impl",
				"com.google.code.kaptcha.impl.ShadowGimpy");
		initParameters.put("kaptcha.textproducer.font.names", "宋体");
		initParameters.put("kaptcha.textproducer.font.color", "blue");
		kaptchaServlet.setInitParameters(initParameters);

	}

}
